package com.sunny.openplatformutils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sunny.openplatformutils.utils.HttpUtil;


/**
 * QQ开放平台工具类
 *
 * @date 2017年5月8日
 *
 * @author Sunny 
 *
 */
public class QQ {
	private static String client_ID, client_Sercret, redirect_URI;
	private static final String userInfoURL = "https://graph.qq.com/user/get_user_info";
	private static final String accessTokenURL = "https://graph.qq.com/oauth2.0/token";
	private static final String openIdURL = "https://graph.qq.com/oauth2.0/me";
	private static Logger logger = LoggerFactory.getLogger(QQ.class);
		
	public static void init(String clientId, String clientSercret, String redirectUri) {
		client_ID = clientId;
		client_Sercret = clientSercret;
		redirect_URI = redirectUri;
	}
	
	public static String getAccessToken(String code) {
		try {
			StringBuilder url = new StringBuilder(accessTokenURL)
				.append("?grant_type=authorization_code")
				.append("&client_id=").append(client_ID)
				.append("&client_secret=").append(client_Sercret)
				.append("&code=").append(code)
				.append("&redirect_uri=").append(redirect_URI);
			
			String tokenStr = HttpUtil.get(url.toString());
			int beginIndex = tokenStr.indexOf("access_token=") + 13;
			int endIndex = tokenStr.indexOf("&", beginIndex);
			return tokenStr.substring(beginIndex, endIndex);
		} catch (Exception e) {
			logger.error(e.getMessage() + ":" + e.getStackTrace());
			return "";
		}
	}
	
	/**
	 * 取用户开放平台信息
	 * @param accessToken
	 * @return <p>{"client_id":"YOUR_APPID", "openid":"YOUR_OPENID", "unioid":"YOUR_UNIONID"}</p>
	 */
	public static String getOpenInfo(String accessToken) {
		try {
			StringBuilder url = new StringBuilder(openIdURL)
				.append("?access_token=").append(accessToken)
				.append("&unionid=1");
			
			String openIdJson = HttpUtil.get(url.toString());
			return openIdJson.replaceAll("callback|\\(|\\)|;", "");
		} catch (Exception e) {
			logger.error(e.getMessage() + ":" + e.getStackTrace());
			return "";
		}
	}
	
	public static String getUserInfo(String accessToken, String openId) {
		try {
			StringBuilder url = new StringBuilder(userInfoURL)
					.append("?access_token=").append(accessToken)
					.append("&oauth_consumer_key=").append(client_ID)
					.append("&openid=").append(openId)
					.append("&format=json");
			return HttpUtil.get(url.toString());
		} catch (Exception e) {
			logger.error(e.getMessage() + ":" + e.getStackTrace());
			return "";
		}
	}
	
}
